﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

public class CallBackGroup
{
    /// <summary>
    /// 回调表
    /// </summary>
    private ArrayList _callbackTable = new ArrayList();
    /// <summary>
    /// 回收索引堆栈
    /// </summary>
    private Stack<int> _indexStack = new Stack<int>();

    public CallBackGroup()
    {
    }

    /// <summary>
    /// 向回调组里增加一个回调 
    /// </summary>
    /// <param name="callback">回调</param>
    /// <returns>回调索引</returns>
    public int Add(CallBack callback)
    {
        int index = 0;
        if (_indexStack.Count < 1)
        {
            index = _callbackTable.Count;
        }
        else
        {
            index = (int)_indexStack.Pop();
        }
        _callbackTable.Insert(index, callback);

        return index;
    }

    /// <summary>
    /// 根据索引移除回调
    /// </summary>
    /// <param name="index"></param>
    public void Remove(int index)
    {
        //置对应索引位置为空
        _callbackTable[index] = null;
        //回收索引编号 如果已经回收的，就不需要再回收，避免回收序号重复，导致派发的序号重复
        if (_indexStack.Contains(index) == false)
        {
            _indexStack.Push(index);
        }
    }

    public void DoCallBack(string PropertiesName, object PropertiesValue, Boolean isAdd)
    {
        DoCallBack(PropertiesName, PropertiesValue, isAdd, false);
    }
    public void DoCallBack(string PropertiesName, object PropertiesValue, Boolean isAdd, Boolean isUpdate)
    {
        for (int i = 0; i < _callbackTable.Count; i++)
        {
            CallBack callback = _callbackTable[i] as CallBack;
            callback._args[0] = PropertiesName;
            callback._args[1]  = PropertiesValue;

            callback.Call(isAdd, isUpdate);
        }
    }

    /// <summary>
    /// 检查是否有相同回调，如果有返回所在索引
    /// </summary>
    /// <param name="callback"></param>
    /// <returns></returns>
    public int CheckSame(CallBack callback)
    {
        for (int i = 0; i < _callbackTable.Count; i++)
        {
            if (_callbackTable[i] != null &&
                (_callbackTable[i] as CallBack).IsSame(callback))
            {
                return i;
            }
        }
        return -1;
    }


}
